package com.landis.temple.mobile;

import android.app.ListActivity;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.SimpleCursorAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemSelectedListener;

/**
 * Activity to handle the search and addition of stories from the remote database
 * 
 * @author John Landis 
 * @author Anton Kronaj
 *
 */
public class SearchActivity extends ListActivity implements OnClickListener 
{
    private static final String TAG = "SearchActivity";
    
    // Default invalid values
    private long author_id  = -1;
    private int searchType = 0;
    private TextView userView;      // for the username display
    private SimpleCursorAdapter adapter;
    
    // Context Menu Options
    private static final int ADD = Menu.FIRST + 1;
    private static final int CANCEL_ID = Menu.FIRST + 2;
    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        Log.d( TAG , "in onCreate" );

        super.onCreate( savedInstanceState );
        setContentView( R.layout.search );

        userView = (TextView) findViewById( R.id.username );
        if(TwitterLibrary.userName != null) userView.setText( TwitterLibrary.userName );

        
        // Sets up spinner with author and story options for search
        Spinner spinner = (Spinner) findViewById(R.id.spinner1);
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
                this, R.array.search_array, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
        
        spinner.setOnItemSelectedListener(new ItemSelectedListener());
        
        registerForContextMenu(getListView());
        
        // Sets onclick listener for searching
        findViewById(R.id.search_button).setOnClickListener(this);
                
        author_id = getIntent().getExtras().getLong("author_id");
        
        Log.d( TAG , "author_id : " + author_id );        
        
        // Return if invalid values supplied
        if( author_id == -1 ) finish();
    }
    
    /**
     * 
     * Sets up context menu for long click options - Add story
     * 
     */
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo)
    {
        super.onCreateContextMenu(menu, v, menuInfo);
        menu.setHeaderTitle(R.string.app_name);
        menu.add(0, ADD, 0, R.string.add );
        menu.add(0, CANCEL_ID, 0, R.string.menu_cancel );
    }
    
    @Override
    public boolean onContextItemSelected(MenuItem item) 
    {
        // Cancels the action
        if( item.getItemId() == CANCEL_ID ) return true;
        
        Log.d( TAG , "onContextItemSelected : " + item.getItemId() );
        AdapterContextMenuInfo story = (AdapterContextMenuInfo) item.getMenuInfo();
        Log.d( TAG , "onContextItemSelected : " + story.id );
        
        // Get current stories and move to selected position
        Cursor now = adapter.getCursor();
        now.moveToPosition(story.position);
        Log.d( TAG , "pos 3 : " + now.getString(3));
        Log.d( TAG , "pos 2 : " + now.getString(2));
        Log.d( TAG , "pos 1 : " + now.getString(1));
        Log.d( TAG , "pos 0 : " + now.getLong(0));
        
        // Set up local database
        TwitterStoryDatabase tsdb = new TwitterStoryDatabase(this);
        tsdb.open();
        
        // Create story and add chapters
        long id = tsdb.getAuthorId(now.getString(1));
        long storyId = tsdb.createStory(id, now.getString(2));
        
        Cursor chapters = MySQLAccess.getChapters( now.getString(2) );
        
        while( chapters.moveToNext() )
        {
            Log.d( TAG , "creating chapter" ); 
            tsdb.createChapter( storyId , chapters.getLong(2), chapters.getString(4));
        }
        
        tsdb.close();
        
        return super.onContextItemSelected(item);
    }

    /**
     * story or chapter is created on button click
     * 
     * @see android.view.View.OnClickListener#onClick(android.view.View)
     */
    @Override
    public void onClick(View button) 
    {
        String text = ( (EditText) findViewById(R.id.search_text) ).getText().toString();        
        Log.d( TAG , "searchType = " + searchType );
        Cursor curse = null;
        
        switch( searchType ) 
        {
            case 0: 
                curse = MySQLAccess.searchAuthorsStories(text);                
                break;
            case 1:
                curse = MySQLAccess.searchStories(text);
                break;
        }
        
        startManagingCursor(curse);
        
        if( curse != null )
        {
            // xml defined views
            int to[] = new int[] {  R.id.story_id           , 
                                    R.id.story_author       , 
                                    R.id.story_title        , 
                                    R.id.story_date_created };
            
            // columns 
            String[] from = curse.getColumnNames();
            
            adapter = new SimpleCursorAdapter( this           , 
                                               R.layout.books , 
                                               curse      , 
                                               from           , 
                                               to             );
            setListAdapter(adapter);
        }
    }
    
    private class ItemSelectedListener implements OnItemSelectedListener 
    {

        public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) 
        {
          Toast.makeText(parent.getContext(), "Searching on " + parent.getItemAtPosition(pos).toString(), Toast.LENGTH_LONG).show();
          searchType = pos;
        }

        public void onNothingSelected(AdapterView parent) 
        {
          // Do nothing.
        }
    }

    // Activity Life Cycle Functions 
    // Unchanged except for added logging information
    
    @Override
    protected void onDestroy() 
    {
        Log.d( TAG , "in onDestroy" );
        super.onDestroy();
    }
    
    @Override
    protected void onPause() 
    {
        Log.d( TAG , "in onPause" );
        super.onPause();
    }

    @Override
    protected void onRestart() 
    {
        Log.d( TAG , "in onRestart" );
        super.onRestart();
    }

    @Override
    protected void onResume() 
    {
        Log.d( TAG , "in onResume" );
        super.onResume();
    }

    @Override
    protected void onStart() 
    {
        Log.d( TAG , "in onStart" );
        super.onStart();
    }

    @Override
    protected void onStop() 
    {
        Log.d( TAG , "in onStop" );
        super.onStop();
    }
}

